package com.example.pingke;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TabHost;
import android.widget.TextView;

public class MainActivity extends FragmentActivity {
	private TabHost mTabHost;
	private View indicator;
	private Fragment indexFragment;

	private FragmentTransaction ft;
	private int currentTab = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mTabHost =  (TabHost) findViewById(android.R.id.tabhost);
		indicator = getIndicatorView("主页", R.layout.main_indicator);
		mTabHost.setup();

		TabHost.OnTabChangeListener tabChangeListener = new TabHost.OnTabChangeListener() {

			@Override
			public void onTabChanged(String tabId) {
				android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
				indexFragment = fm.findFragmentByTag("index");
				ft = fm.beginTransaction();
				if (indexFragment != null) {
					ft.detach(indexFragment);
				}

				if (tabId.equalsIgnoreCase("index")) {
					isTabIndex();
					currentTab = 1;
				} else {
					switch (currentTab) {
					case 1:
						isTabIndex();
						break;
					default:
						isTabIndex();
					}
				}
				ft.commit();
			}
		};
		mTabHost.setCurrentTab(0);
		mTabHost.setOnTabChangedListener(tabChangeListener);
		initTab();
	}

	public void isTabIndex() {
		if (indexFragment == null) {
			ft.add(R.id.container, new IndexFragment(), "index");
		} else {
			ft.attach(indexFragment);
		}
	}

	private void initTab() {
		TabHost.TabSpec indexTabSpec = mTabHost.newTabSpec("index");
		indicator = getIndicatorView("主页", R.layout.main_indicator);
		indexTabSpec.setIndicator(indicator);
		indexTabSpec.setContent(R.id.tab1);
		mTabHost.addTab(indexTabSpec);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private View getIndicatorView(String name, int layoutId) {
		View v = getLayoutInflater().inflate(layoutId, null);
		TextView tx = (TextView) v.findViewById(R.id.indicatorText);
		tx.setText(name);
		return v;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mTabHost = null;
	}

}
